package cn.kgc.util;

import cn.hutool.json.JSONUtil;
import cn.kgc.entity.Messageinfo;
import cn.kgc.service.SenderMessageInfoService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author wangyue
 * @version 1.0
 * 发送消息的实体类
 */
@Component
@SuppressWarnings("all")
public class MessageinfoSender {

    @Value("${mq.serviceName}")
    private String serivceName;
    @Resource
    private SenderMessageInfoService senderMessageInfoService;
    @Resource
    private RabbitTemplate rabbitTemplate;

    public void sendMessage(String exchange,String routingKey,Object message,int delay){
        //将要发送的消息转为json格式的字符串
        String jsonString= JSONUtil.toJsonStr(message);
        //1 将发送的消息保存到数据库中
        Messageinfo messageinfo=
                senderMessageInfoService.messageSendReady(exchange,routingKey,jsonString,serivceName,delay);
        //2将消息发送到mq中
        MessageProperties messageProperties=new MessageProperties();
        messageProperties.setContentType("application/json");
        //指定消息发送的次数
        messageProperties.setHeader("sequence",messageinfo.getSequence());
        //设置消息的延迟时间(告诉RabbitMQ，这条消息需要延迟多久)
        messageProperties.setDelay(delay);
        //设置消息的延迟时间(给我们自己使用的,我们要使用这个参数判断消息是否是延迟消息)
        messageProperties.setHeader("delay",delay);
        //封装发送的消息(注意发送到RabbitMQ中的消息并不是数据库中的对象！！！！)
        Message rabbitMessage=new Message(
                jsonString.getBytes(StandardCharsets.UTF_8),
                messageProperties
        );
        //调用方法发送消息
        rabbitTemplate.convertAndSend(exchange,routingKey,
                rabbitMessage,new CorrelationData(messageinfo.getId())
        );
    }

    public void sendMessage(String exchange,String routingKey,Object message){
         sendMessage(exchange,routingKey,message,0);
    }
}
